import requests
import json


api_url = "http://127.0.0.1/v1/chat-messages"

api_key = "app-PMFC3fiTtJKuLnkVBkrGqxKy"


# 设置请求头
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"  # 如果接口需要 Bearer Token 认证
}

# 要发送的消息内容
data_raw = {
    "inputs": {},
    "query": "Convert these features into a sales pitch in under 100 words: 24hr battery, noise-cancelling, sweatproof.",
    "response_mode": "streaming",
    "conversation_id": "",
    "user": "yaaakaaang",
    "files": [
        {
            "type": "image",
            "transfer_method": "remote_url",
            "url": "https://cloud.dify.ai/logo/logo-site.png"
        }
    ]
}

# 发送 POST 请求，获取流式响应
response = requests.post(api_url, headers=headers, data=json.dumps(data_raw), stream=True)

try:
    # 逐条读取事件流
    for line in response.iter_lines():
        if line:
            # 每行是一个完整的事件，首先去掉事件前后的空白字符
            line = line.decode('utf-8').strip()

            if line.startswith("data:"):
                # 提取 JSON 数据部分
                json_data = line[len("data:"):].strip()
                try:
                    parsed_data = json.loads(json_data)
                    print("回复内容：", parsed_data.get('answer', '无答案'))
                except json.JSONDecodeError:
                    print("无法解析 JSON 数据:", json_data)
except requests.exceptions.HTTPError as http_err:
    print(f"HTTP 错误发生: {http_err}")
except Exception as err:
    print(f"其他错误发生: {err}")